// 浅拷贝 Object.assign()

// 深拷贝 JSON.parse(JSON.stringify(object))
function deepClone(source) {
  if (typeof source != 'object') return
  let target = Array.isArray(source) ? [] : {}
  for (let key in source) {

      if (typeof source[key] == 'object' && source[key] != null) {
          target[key] = deepClone(source[key])
      } else {
          target[key] = source[key]
      }

  }
  return target
}

// 检测对象是否循环引用 过滤循环引用对象 - 同时也是深拷贝
function circular(source) {
  const cache = new WeakMap();
  return (function reCheck (value, path) {
      // 1. 判断对象的类型
      if (
          typeof value == 'object' &&
          value !== null &&
          !(value instanceof String) &&
          !(value instanceof Symbol) && 
          !(value instanceof Date) && 
          !(value instanceof RegExp)
      ) {
          if (cache.has(value)) {
              return path
          }

          cache.set(value, path)

          let temp
          if (Array.isArray(value)) {
              temp = []
              for (let i in value) {
                  temp[i] = reCheck(value[i], `${path}${i}`)
              }
          } else {
              temp = {}
              for (let key in value) {
                  temp[key] = reCheck(value[key], path)
              }
          }

          return temp
      } else {
          return value
      }
  })(source, '$');
}


const testObject = { name: 'mal', age: 18, t: { name2: 'sss', age: 10 } }
let a = {name: 'mal'}
let b = {parent: a, age: 18}
a.child = b

const cir = circular(testObject)
testObject.t.name2 = 'xxxx'
cir.age = 19
console.log(111, testObject);
console.log(222, cir)

const test2 = deepClone(testObject)
